package edu.fsu.cs.SHPE;

import java.net.ConnectException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class TracksContainer extends ArrayList<Conference> {

	private static final long serialVersionUID = 8230025528611178336L;
	private Conference tmpConference;
	private final static String TAG = "SHPE.TracksContainer";
	
	
	public TracksContainer(String url) throws ConnectException{
		if(!parseXml(url))
			throw new ConnectException();
	}

	public String[] getStrings(){
		String [] strings = new String[this.size()];
		
		for(int x = 0; x < this.size(); x++){
			strings[x] = this.get(x).getName();
			Log.i(TAG, "getting " + strings[x]);
			
		}
		
		return strings;
	}
	
	
	private boolean parseXml(String url){

		Log.i(TAG, "<" + url + ">");

		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			// Multiple conference testserver
			//"http://ww2.cs.fsu.edu/~sposaro/test/index.html"

			URL sourceUrl = new URL(url);
			ConferenceXMLHandler conferenceHandler = new ConferenceXMLHandler();
			xr.setContentHandler(conferenceHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));	

		} catch (Exception e) {
			return false;
		}

		return true;

	}

	public class ConferenceXMLHandler extends DefaultHandler {


		public void startDocument() throws SAXException {
			Log.i(TAG, "Document processing started");
			
			tmpConference = new Conference();
			tmpConference.setName("All Tracks");
			tmpConference.setId(0);
			add(tmpConference);
			
			tmpConference = null;
		}


		public void endDocument() throws SAXException {
			Log.i("HANDLER", "Document processing finished");

			if(tmpConference != null)
				add(tmpConference);
		}


		public void startElement(String uri, String localName, String qName, Attributes attributes){
			Log.i("HANDLER", "in element " + localName + " qName " + qName + " uri " + uri);


			if(localName.equalsIgnoreCase("conference-track")){

				if(tmpConference != null){
					add(tmpConference);
				}


				tmpConference = null;
				tmpConference = new Conference();

				if(attributes.getValue("name") != null)
					tmpConference.setName(attributes.getValue("name"));

				tmpConference.setId(Long.parseLong(attributes.getValue("id")));

			}
		}
	}
}
